package com.zjun;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * 单例对象容器
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Singleton {
    private static final ConcurrentHashMap<String,Object> SINGLE_OBJECT_POOL = new ConcurrentHashMap<>();

    /**
     * 根据key获取单例对象
     * @param key
     * @return
     * @param <T>
     */
    public static <T> T get(String key){
        Object result = SINGLE_OBJECT_POOL.get(key);
        return result==null?null:(T)result;
    }

    /**
     * 将对象放入容器中,无key用单例的class名作为key
     */
    public static void put(Object value){
        put(value.getClass().getName(),value);
    }
    public static void put(String key,Object value){
        SINGLE_OBJECT_POOL.put(key,value);
    }
    /**
     * 根据key获取实力对象,如果为空则使用supplier构建对象并放入容器
     */
    public static <T> T get(String key, Supplier<T> supplier){
        Object result = SINGLE_OBJECT_POOL.get(key);
        if (result==null && (result = supplier.get())!=null){
            SINGLE_OBJECT_POOL.put(key,result);
        }
        return result==null?null: (T) result;
    }
}
